#include "apue.h"
#include <string.h>
#include <fcntl.h>
#include "errno.h"

const int BUFFSIZE = 2048;
const int FILESIZE = 100 * 1024 * 1024;

void ProcBar(int cur, int total, int flag) {
    int idx = 0, i;
    // str用来盛放字符进度
    // proc用来盛放等号进度
    char str[115], proc[102], ch;
    bzero(str, 115);
    bzero(proc, 102);

    double rate = cur > total ? 100.0 : (cur * 100.0) / total;
    idx = (int)rate;
    for (i = 0; i < idx; i++)
        str[i] = '=';
    str[i] = '>';

    if (flag % 3 == 0)
        ch = '\\';
    else if (flag % 3 == 1)
        ch = '-';
    else
        ch = '/';

    // printf("\r");
    printf("|%-101s| %c %6.2f%%\r", str, ch, rate);
    fflush(stdout);
}

int main() {
    int n;
    int buff[BUFFSIZE];
    int fd_src, fd_dest;
    fd_src = open("src.txt", O_RDONLY);
    if (fd_src == -1)
        err_sys("Open source file error");

    fd_dest = open("dest.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd_dest == -1) 
        err_sys("Create destination error");

    int sum = 0, flag = 0;
    while ((n = read(fd_src, buff, BUFFSIZE)) >= 0) {
        if (n == 0) {
            ProcBar(sum, FILESIZE, flag);
            break;
        }
        if ((n = write(fd_dest, buff, n)) < 0) {
            err_sys("Write data error");
        }
        ProcBar(sum, FILESIZE, flag);
        sum += n;
        flag ++;
    }

    close(fd_src);
    close(fd_dest);

    if (n == -1)
        err_sys("Read data error");

    return 0;
}
